package com.czt.mail.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author tangchao
 * 可以通过注解的方式拦截 annotations = {RestController.class, Controller.class}
 * 包扫描 basePackages = "com.jeesite.modules", //拦截modules下的所有子包
 */
//@ControllerAdvice(basePackages = "com.czt.mail")
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public <T> AjaxResult<T> handleException(Exception ex) {
        // 创建一个自定义的异常响应对象
        AjaxResult<T> ajaxResult = new AjaxResult<>();
        if(ex instanceof BusinessException){
            BusinessException businessException = (BusinessException) ex;
            ajaxResult.setMsg(businessException.getMsg());
            ajaxResult.setCode(businessException.getCode());
        }else{
            ajaxResult.setMsg("500");
            ajaxResult.setCode("系统错误");
        }
        return ajaxResult;
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public AjaxResult<String> handleBusinessException(BusinessException ex) {
        String code = ex.getCode();
        String msg = ex.getMsg();
        return AjaxResult.error(code, msg);
    }
}
